package com.example.s09_redis.service;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Set;

// Redis操作的封装类
// 可以存入对象

@Service
public class RedisService
{
    @Autowired
    private RedisTemplate redisTemplate;


    // 存入
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
//            logger.error("set error: key {}, value {}",key,value,e);
            System.out.println(""+e.getMessage());
        }
        return result;
    }

    // 取出
    public Object get(final String key)
    {
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        return operations.get(key);
    }

    // 移除
    public void remove(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0) {
            redisTemplate.delete(keys);
        }
    }


}
